// pages/search/search.js

Page({
  /**
   * 页面的初始数据
   */
  data: {
    searchValue: '',
    showActionSheetFlag: false,
    isFocused: false,
    historyList: [],
    filteredHistoryList: [],
    loading: false,
    // 左滑删除相关
    swipeStates: [], // 每个列表项的左滑状态
    touchStartX: 0,
    touchStartTime: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('搜索页面加载完成');
    // 从数据库获取选型历史
    this.getCalculationHistory();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('搜索页面显示');
    // 每次显示页面时刷新选型历史
    this.getCalculationHistory();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },

  /**
   * 搜索输入处理
   */
  onSearchInput: function(e) {
    const value = e.detail.value.toLowerCase();
    this.setData({
      searchValue: value
    });

    // 过滤历史记录
    const filteredList = this.data.historyList.filter(item => {
      const machineName = item.machineName.toLowerCase();
      const axisName = item.axisName.toLowerCase();
      return machineName.includes(value) || axisName.includes(value);
    });

    // 重置左滑状态
    const swipeStates = new Array(filteredList.length).fill(false);

    this.setData({
      filteredHistoryList: filteredList,
      swipeStates: swipeStates
    });
  },

  /**
   * 处理搜索框聚焦
   */
  onSearchFocus: function() {
    console.log('搜索框聚焦');
    this.setData({
      isFocused: true
    });
  },

  /**
   * 处理搜索框失焦
   */
  onSearchBlur: function() {
    console.log('搜索框失焦');
    this.setData({
      isFocused: false
    });
  },

  /**
   * 获取选型历史
   */
  getCalculationHistory: function() {
    this.setData({
      loading: true
    });

    // 调用云函数获取选型历史
    wx.cloud.callFunction({
      name: 'motor_db',
      data: {
        action: 'get_calculation_history'
      }
    }).then(res => {
      console.log('获取选型历史成功:', res.result);
      
      if (res.result.success) {
        const historyList = res.result.data.map(item => ({
          _id: item._id, // 保留原始ID用于删除
          id: item._id,
          machineName: item.formData?.machineName || '未知机器',
          axisName: item.formData?.axisName || '未知轴',
          date: this.formatTimestamp(item.createTime),
          status: item.selectedMotor ? 'completed' : 'incomplete' // 根据是否选择了电机判断状态
        }));

        // 初始化左滑状态数组
        const swipeStates = new Array(historyList.length).fill(false);

        this.setData({
          historyList: historyList,
          filteredHistoryList: historyList,
          swipeStates: swipeStates,
          loading: false
        });
      } else {
        console.error('获取选型历史失败:', res.result.error);
        this.getLocalCalculationHistory();
      }
    }).catch(err => {
      console.error('调用云函数失败:', err);
      // 如果云函数调用失败，尝试获取本地缓存
      this.getLocalCalculationHistory();
    });
  },

  /**
   * 获取本地缓存的选型历史（备用方案）
   */
  getLocalCalculationHistory: function() {
    try {
      const localHistory = wx.getStorageSync('local_calculation_history') || [];
      const swipeStates = new Array(localHistory.length).fill(false);
      
      this.setData({
        historyList: localHistory,
        filteredHistoryList: localHistory,
        swipeStates: swipeStates,
        loading: false
      });
    } catch (error) {
      console.error('获取本地选型历史失败:', error);
      this.setData({
        historyList: [],
        filteredHistoryList: [],
        swipeStates: [],
        loading: false
      });
    }
  },

  /**
   * 使用历史记录
   */
  useHistory: function(e) {
    const { machine, axis } = e.currentTarget.dataset;
    console.log('查看选型详情:', machine, axis);
    
    // 跳转到搜索详情页面，传递机器名和轴名参数
    wx.navigateTo({
      url: `/pages/search-detail/search-detail?machineName=${encodeURIComponent(machine)}&axisName=${encodeURIComponent(axis)}`
    });
  },

  /**
   * 清空数据库和本地的选型历史
   */
  clearDatabaseHistory: function() {
    // 调用云函数清空选型历史
    wx.cloud.callFunction({
      name: 'motor_db',
      data: {
        action: 'clear_calculation_history'
      }
    }).then(res => {
      console.log('清空选型历史结果:', res.result);
      
      if (res.result.success) {
        console.log('清空数据库选型历史成功:', res.result.message);
        this.clearLocalHistory();
      } else {
        console.error('清空数据库选型历史失败:', res.result.error);
        this.clearLocalHistory();
      }
    }).catch(err => {
      console.error('调用云函数失败:', err);
      this.clearLocalHistory();
    });
  },

  /**
   * 清空本地选型历史
   */
  clearLocalHistory: function() {
    try {
      wx.removeStorageSync('local_calculation_history');
    } catch (error) {
      console.error('清空本地选型历史失败:', error);
    }

    // 添加清空动画
    const historyItems = this.selectAllComponents('.history-item');
    
    // 逐个添加淡出动画
    this.data.historyList.forEach((item, index) => {
      setTimeout(() => {
        // 这里可以添加动画效果
        if (index === this.data.historyList.length - 1) {
          // 最后一个元素动画完成后清空数据
          setTimeout(() => {
            this.setData({
              historyList: [],
              filteredHistoryList: [],
              swipeStates: []
            });
            
            wx.showToast({
              title: '清空成功',
              icon: 'success'
            });
          }, 300);
        }
      }, index * 100);
    });
  },

  /**
   * 显示操作面板
   */
  showActionSheet: function() {
    console.log('显示操作面板');
    this.setData({
      showActionSheetFlag: true
    });
  },

  /**
   * 关闭操作面板
   */
  closeActionSheet: function() {
    console.log('关闭操作面板');
    this.setData({
      showActionSheetFlag: false
    });
  },

  /**
   * 选择电机类型
   */
  selectMotorType: function(e) {
    const type = e.currentTarget.dataset.type;
    console.log('选择电机类型:', type);
    
    this.closeActionSheet();
    
    let message = '';
    if (type === 'linear') {
      message = '跳转到直线电机选型页面';
    } else if (type === 'rotary') {
      message = '跳转到直驱旋转电机选型页面';
    }

    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });

    wx.navigateTo({
      url: '/pages/calculate/calculate'
    });
  },

  /**
   * 格式化时间戳为可读格式
   */
  formatTimestamp: function(timestamp) {
    const date = new Date(timestamp);
    return this.formatDate(date);
  },

  /**
   * 格式化日期
   */
  formatDate: function(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();

    return `${year}年${month}月${day}日 ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
  },

  /**
   * 触摸开始 - 左滑删除
   */
  onTouchStart: function(e) {
    const touch = e.touches[0];
    this.setData({
      touchStartX: touch.clientX,
      touchStartTime: Date.now()
    });
  },

  /**
   * 触摸移动 - 左滑删除
   */
  onTouchMove: function(e) {
    const touch = e.touches[0];
    const index = e.currentTarget.dataset.index;
    const deltaX = this.data.touchStartX - touch.clientX;
    const swipeStates = [...this.data.swipeStates];

    // 向左滑动超过50px且时间不超过300ms，显示删除按钮
    if (deltaX > 50 && Date.now() - this.data.touchStartTime < 300) {
      swipeStates[index] = true;
    } else if (deltaX < -20) {
      // 向右滑动隐藏删除按钮
      swipeStates[index] = false;
    }

    this.setData({
      swipeStates: swipeStates
    });
  },

  /**
   * 触摸结束 - 左滑删除
   */
  onTouchEnd: function(e) {
    // 清空触摸状态
    this.setData({
      touchStartX: 0,
      touchStartTime: 0
    });
  },

  /**
   * 删除历史记录项
   */
  deleteHistoryItem: function(e) {
    const index = e.currentTarget.dataset.index;
    const recordId = e.currentTarget.dataset.id;
    const item = this.data.filteredHistoryList[index];

    // 显示确认删除对话框
    wx.showModal({
      title: '确认删除',
      content: `确定要删除选型记录"${item.machineName} - ${item.axisName}"吗？`,
      confirmText: '删除',
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          this.confirmDeleteItem(recordId, index);
        } else {
          // 用户取消，恢复左滑状态
          const swipeStates = [...this.data.swipeStates];
          swipeStates[index] = false;
          this.setData({
            swipeStates: swipeStates
          });
        }
      }
    });
  },

  /**
   * 确认删除历史记录项
   */
  confirmDeleteItem: function(recordId, index) {
    // 显示加载状态
    wx.showLoading({
      title: '删除中...'
    });

    // 调用云函数删除记录
    wx.cloud.callFunction({
      name: 'motor_db',
      data: {
        action: 'delete_calculation',
        data: {
          recordId: recordId
        }
      }
    }).then(res => {
      wx.hideLoading();
      
      if (res.result.success) {
        // 删除成功，更新本地数据
        const historyList = this.data.historyList.filter(item => item._id !== recordId);
        const filteredHistoryList = this.data.filteredHistoryList.filter(item => item._id !== recordId);
        const swipeStates = this.data.swipeStates.filter((_, i) => i !== index);

        this.setData({
          historyList: historyList,
          filteredHistoryList: filteredHistoryList,
          swipeStates: swipeStates
        });

        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: res.result.message || '删除失败',
          icon: 'error'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('删除记录失败:', err);
      wx.showToast({
        title: '删除失败',
        icon: 'error'
      });
    });
  },

  /**
   * 重置所有左滑状态
   */
  resetSwipeStates: function() {
    const swipeStates = new Array(this.data.filteredHistoryList.length).fill(false);
    this.setData({
      swipeStates: swipeStates
    });
  }
}); 